#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>
#include<stdlib.h>
struct ListNode {
    int val;
    struct ListNode* next;
    
};
struct ListNode* getIntersectionNode(struct ListNode* headA,
    struct ListNode* headB) {
    struct ListNode* A = headA;
    struct ListNode* B = headB;
    struct ListNode* A1 = headA;
    struct ListNode* B1 = headB;
    int _acnt = 0;
    while (A) {
        _acnt ++;
        A = A->next;
    
    }
    int _bcnt = 0;
    while (B) {
        _bcnt++;
        B = B->next;
       
        
    }
    while (A1 && B1)
    {
        if (_acnt > _bcnt) {
            while (_acnt!=_bcnt)
            {
                _acnt--;
                A1 = A1->next;
          }
            

        }
        else if (_acnt < _bcnt)
        {
            while (_acnt != _bcnt)
            {
                B1 = B1->next;
                _bcnt--;
            }
            
        }
        else {
            while (A1 && B1)
            {
                if (A1 == B1)
                {
                    return A1;
                }
                A1 = A1->next;
                B1 = B1->next;
            }
        }
    }
    
    return  NULL;
}

int main()
{
    struct ListNode* p1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* p2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* p3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* p4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* p5 = (struct ListNode*)malloc(sizeof(struct ListNode));
    p1->val = 4;
    p2->val = 1;
    p3->val = 8;
    p4->val = 4;
    p5->val = 5;
    p1->next = p2;
    p2->next = p3;
    p3->next = p4;
    p4->next = p5;
    p5->next = NULL;
    struct ListNode* m1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* m2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* m3 = (struct ListNode*)malloc(sizeof(struct ListNode));
 
    m1->val = 5;
    m2->val = 6;
    m3->val = 1;
   
    m1->next = m2;
    m2->next = m3;
    m3->next = p3;
    p3->next = p4;
    p4->next = p5;
    p5->next = NULL;

    getIntersectionNode(p1, m1);
    return 0;
}